package org.budo.filestore.qiniu.util;

import java.net.URL;
import java.security.MessageDigest;

import org.apache.commons.codec.binary.Hex;
import org.budo.support.assertion.Assert;
import org.budo.support.java.net.util.JavaNetUrlUtil;

/**
 * @author lmw
 */
public class QiniuUtil {
    public static String antiLeechAccessUrl(String antiLeechKey, Integer antiLeechDuration, String qiniuUrl) {
        Assert.notNull(antiLeechDuration, "QiniuUtil#antiLeechAccessUrl, antiLeechDuration is null");

        URL url = JavaNetUrlUtil.newUrl(qiniuUrl);
        String path = url.getPath();
        long timestampNow = System.currentTimeMillis() / 1000 + antiLeechDuration;
        String expireHex = Long.toHexString(timestampNow);

        String toSignStr = String.format("%s%s%s", antiLeechKey, path, expireHex);
        String signedStr = md5ToLower(toSignStr);
        if (url.getQuery() != null) {
            return String.format("%s&sign=%s&t=%s", qiniuUrl, signedStr, expireHex);
        } else {
            return String.format("%s?sign=%s&t=%s", qiniuUrl, signedStr, expireHex);
        }
    }

    public static String md5ToLower(String string) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(string.getBytes("UTF-8"));
            byte[] md5Bytes = digest.digest();
            return Hex.encodeHexString(md5Bytes);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
